package api

import (
	"html"

	"github.com/gin-gonic/gin"
	"zhonghui/console/warehouse/dbx"
	"zhonghui/console/warehouse/dbx/db_zh_kernel"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/modelx/model_zh_kernel"
	"zhonghui/console/warehouse/respx"

	"zhonghui/console/service"
	"zhonghui/console/structs"
)

func (server *Server) GetGroups(c *gin.Context) {
	user := service.GetUserFromToken(c.GetHeader("Authorization"))
	if user == nil {
		respx.UnAuth(c)
		return
	}

	if !service.CanDo(user.ID, "*:*") {
		respx.Alert(c, "没有权限")
		return
	}

	groups := make([]model_zh_kernel.ConsoleGroups, 0)
	if err := db_zh_kernel.Client().Preload("Managers").Order("id desc").Find(&groups).Error; err != nil {
		respx.Alert(c, "获取管理员组列表错误")
		return
	}

	resp := make([]structs.GetGroupsResp, 0)
	for _, group := range groups {

		resp = append(resp, structs.GetGroupsResp{
			Id:            group.ID,
			Name:          group.Name,
			ManagersCount: len(group.Managers),
			CreatedAt:     group.CreatedAt.Format(helperx.TimeLayoutCommon),
		})
	}

	respx.Success(c, resp, nil)
}

func (server *Server) PostGroups(c *gin.Context) {
	req := structs.PostGroupsReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		respx.Bad(c, err)
		return
	}

	user := service.GetUserFromToken(c.GetHeader("Authorization"))
	if user == nil {
		respx.UnAuth(c)
		return
	}

	if !service.CanDo(user.ID, "*:*") {
		respx.Alert(c, "没有权限")
		return
	}

	group := model_zh_kernel.ConsoleGroups{}
	if err := db_zh_kernel.Client().Where("name = ?", req.Name).Take(&group).Error; err == nil {
		respx.Alert(c, "该名称的组已经存在了")
		return
	}

	newGroup := model_zh_kernel.ConsoleGroups{
		Name: html.EscapeString(req.Name),
	}
	if err := db_zh_kernel.Client().Save(&newGroup).Error; err != nil {
		respx.Alert(c, "创建失败，请重试")
		return
	}

	respx.Success(c, nil, nil)
}

func (server *Server) DeleteGroups(c *gin.Context) {
	user := service.GetUserFromToken(c.GetHeader("Authorization"))
	if user == nil {
		respx.UnAuth(c)
		return
	}

	if !service.CanDo(user.ID, "*:*") {
		respx.Alert(c, "没有权限")
		return
	}

	// 超级管理员组不允许更改
	if c.Param("id") == "1" {
		respx.Alert(c, "超级管理员组不允许更改")
	}

	conn := dbx.NewTx(db_zh_kernel.Client().Begin())
	defer conn.End()

	if err := conn.Tx.Where("id = ?", c.Param("id")).Delete(model_zh_kernel.ConsoleGroups{}).Error; err != nil {
		respx.Alert(c, "删除失败，请重试")
		return
	}
	if err := conn.Tx.Where("group_id = ?", c.Param("id")).Delete(model_zh_kernel.ConsoleGroupManager{}).Error; err != nil {
		respx.Alert(c, "删除失败，请重试")
		return
	}

	conn.Commit()

	respx.Success(c, nil, nil)
}

func (server *Server) GetGroupsUsers(c *gin.Context) {
	user := service.GetUserFromToken(c.GetHeader("Authorization"))
	if user == nil {
		respx.UnAuth(c)
		return
	}

	if !service.CanDo(user.ID, "*:*") {
		respx.Alert(c, "没有权限")
		return
	}

	group := model_zh_kernel.ConsoleGroups{}
	if err := db_zh_kernel.Client().Preload("Managers").Where("id = ?", c.Param("id")).Take(&group).Error; err != nil {
		respx.Alert(c, "查询群组失败，请重试")
		return
	}

	resp := make([]structs.GetGroupsUsersResp, 0)
	for _, manager := range group.Managers {
		temp := structs.GetGroupsUsersResp{
			Id:        manager.ID,
			Phone:     manager.Phone,
			RealName:  manager.RealName,
			Position:  manager.Position,
			Nickname:  manager.Nickname,
			IsActive:  manager.IsActive == 1,
			CreatedAt: manager.CreatedAt.Format(helperx.TimeLayoutCommon),
		}

		resp = append(resp, temp)
	}

	respx.Success(c, resp, nil)
}

func (server *Server) PostGroupsMembers(c *gin.Context) {
	req := structs.PostGroupsMembersReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		respx.Bad(c, err)
		return
	}

	user := service.GetUserFromToken(c.GetHeader("Authorization"))
	if user == nil {
		respx.UnAuth(c)
		return
	}

	if !service.CanDo(user.ID, "*:*") {
		respx.Alert(c, "没有权限")
		return
	}

	// 查询组
	group := model_zh_kernel.ConsoleGroups{}
	if err := db_zh_kernel.Client().Where("id = ?", c.Param("id")).Take(&group).Error; err != nil {
		respx.Alert(c, "查询群组失败，请重试")
		return
	}

	// 查询用户列表
	managers := make([]model_zh_kernel.ConsoleManager, 0)
	if err := db_zh_kernel.Client().Where("id in (?)", req.UserIds).Find(&managers).Error; err != nil {
		respx.Alert(c, "查询用户列表错误")
		return
	}

	conn := dbx.NewTx(db_zh_kernel.Client().Begin())
	defer conn.End()

	// 清除旧授权
	if err := conn.Tx.Where("group_id = ?", group.ID).Delete(model_zh_kernel.ConsoleGroupManager{}).Error; err != nil {
		respx.Alert(c, "清除旧成员错误，请重试")
		return
	}

	// 添加新授权
	for _, manager := range managers {
		newGroupManager := model_zh_kernel.ConsoleGroupManager{
			GroupID:   group.ID,
			ManagerID: manager.ID,
		}
		if err := conn.Tx.Save(&newGroupManager).Error; err != nil {
			respx.Alert(c, "保存成员错误，请重试")
			return
		}
	}

	conn.Commit()

	respx.Success(c, nil, nil)
}
